import { getListApi } from "@/api/managementCenter/customerManagement";
import { computed } from "vue";
export default function OperationHook(state: Base.GeneraDataType) {
  const { searchForm, tableRef, tableData, loading, keyWord, emit, checkResult, visible } = state;
  const selectRows = computed<Array<DepartmentPersonnel.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const searchHandle = () => {
    searchForm.pageNum = 1;
    getData();
  };
  const getData = () => {
    const params = {
      ...searchForm
    };
    loading.value = true;
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => (loading.value = false));
  };
  const filterMethod = (e: any) => {
    const { option, row } = e;
    if (option.data) {
      if (keyWord.value !== option.data) keyWord.value = option.data;
      return row.shortName.toLowerCase().indexOf(option.data) > -1;
    }
    return true;
  };
  const addHandle = () => {
    const hasIds = checkResult.value.map((t: any) => `${t.customerId},${t.customerShortName}`);
    const selectIds = selectRows.value.map((t: any) => `${t.id},${t.shortName}`);
    const resultIds = Array.from(new Set(hasIds.concat(selectIds)));
    checkResult.value = resultIds.map((t: any) => {
      const res = t.split(",");
      return {
        customerId: res[0],
        customerShortName: res[1]
      };
    });
    tableRef.value.xTable.clearCheckboxRow();
  };
  const checCheckboxkMethod = ({ row }: any) => {
    const flag = checkResult.value.find((t: any) => row.id === t.customerId) || false;
    if (flag) return false;
    else return true;
  };
  const removeHandle = (index: number) => {
    checkResult.value.splice(index, 1);
  };
  const removeAllHandle = () => {
    checkResult.value = [];
  };
  const submitHandle = () => {
    visible.value = false;
    emit("update:value", checkResult.value);
  };
  return {
    searchHandle,
    selectRows,
    getData,
    filterMethod,
    removeHandle,
    submitHandle,
    addHandle,
    removeAllHandle,
    checCheckboxkMethod
  };
}
